// 模拟延迟
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

// 角色权限映射
const ROLE_PERMISSIONS: Record<string, string[]> = {
  // 超级管理员 - 拥有所有权限
  admin: [
    'canAccessHome',
    'canAccessUserManage',
    'canAccessUserList',
    'canAccessHouseManage',
    'canAccessHouseList',
    'canAccessCommunityList',
  ],
  // 运营人员 - 用户管理权限
  operator: ['canAccessHome', 'canAccessUserManage', 'canAccessUserList'],
  // 房源管理员 - 房源相关权限
  houseManager: [
    'canAccessHome',
    'canAccessHouseManage',
    'canAccessHouseList',
    'canAccessCommunityList',
  ],
  // 普通用户 - 仅查看权限
  user: ['canAccessHome'],
};

// 模拟用户数据
const mockUsers = [
  {
    account: 'admin',
    password: 'admin123',
    userName: '超级管理员',
    avatar:
      'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    userid: '00000001',
    email: 'admin@example.com',
    signature: '海纳百川，有容乃大',
    title: '系统管理员',
    group: '万惠券运营组',
    role: 'admin',
    permissions: ROLE_PERMISSIONS.admin,
  },
  {
    account: 'operator',
    password: 'operator123',
    userName: '运营专员',
    avatar:
      'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    userid: '00000002',
    email: 'operator@example.com',
    signature: '努力工作，服务用户',
    title: '运营专员',
    group: '万惠券运营组',
    role: 'operator',
    permissions: ROLE_PERMISSIONS.operator,
  },
  {
    account: 'house',
    password: 'house123',
    userName: '房源管理员',
    avatar:
      'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    userid: '00000003',
    email: 'house@example.com',
    signature: '专注房源管理',
    title: '房源管理员',
    group: '万惠券运营组',
    role: 'houseManager',
    permissions: ROLE_PERMISSIONS.houseManager,
  },
  {
    account: 'user',
    password: 'user123',
    userName: '普通用户',
    avatar:
      'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    userid: '00000004',
    email: 'user@example.com',
    signature: '普通用户',
    title: '访客',
    group: '万惠券运营组',
    role: 'user',
    permissions: ROLE_PERMISSIONS.user,
  },
];


// 生成模拟用户数据
const generateMockUserData = (): any[] => {
  const departments = ['研发部', '销售部', '市场部', '人事部', '财务部'];
  const posts = ['工程师', '设计师', '产品经理', '销售经理', '分析师', '专员'];

  const data = [];

  for (let i = 1; i <= 100; i++) {
    const dept = departments[Math.floor(Math.random() * departments.length)];
    const post = posts[Math.floor(Math.random() * posts.length)];
    const status = i % 3 === 0 ? 2 : 1; // 每第三个用户冻结

    data.push({
      id: i,
      account: `user${i.toString().padStart(3, '0')}`,
      realname: `用户${i.toString().padStart(3, '0')}`,
      sex: i % 2 === 0 ? 1 : 2, // 1: 男, 2: 女
      sex_dictText: i % 2 === 0 ? '男' : '女',
      phone: `138${String(i).padStart(8, '0')}`,
      email: `user${i}@example.com`,
      status: status,
      status_dictText: status === 1 ? '正常' : '冻结',
      avatar: `https://xsgames.co/randomusers/avatar.php?g=pixel&key=${i}`,
      activitiSync: '0',
      createTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
      updateTime: new Date(Date.now() - Math.floor(Math.random() * 5000000000)).toISOString(),
      description: `这是用户 ${i} 的描述`,
      workNo: `W${String(i).padStart(5, '0')}`,
      post: post,
      telephone: `021-${Math.floor(Math.random() * 9000 + 1000)}-${Math.floor(Math.random() * 9000 + 1000)}`,
      address: `上海市${dept.slice(0, 2)}路${Math.floor(Math.random() * 100) + 1}号`,
      birthday: new Date(1980 + Math.floor(Math.random() * 40), Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1).toISOString().split('T')[0],
      idcard: `31010119${String(1980 + Math.floor(Math.random() * 40)).slice(2)}${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}${Math.floor(Math.random() * 1000) + 1000}X`,
      departIds: [Math.floor(Math.random() * 5) + 1, Math.floor(Math.random() * 5) + 1].join(','),
      departNames: dept,
      userAgentId: i + 100,
      userAgentName: `代理人${i}`,
      userAgentStartTime: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
      userAgentEndTime: new Date(Date.now() + Math.floor(Math.random() * 10000000000)).toISOString(),
      userAgentStatus: '1',
      thirdId: `third_${i}`,
      thirdType: 'wechat',
      regEmail: `reg_user${i}@example.com`,
      regPhone: `139${String(i).padStart(8, '0')}`,
      regUserType: '1',
      regUserStatus: '1',
      regUserSource: '1',
      regUserRemark: `注册备注 ${i}`,
      regUserAgent: `注册代理人${i}`,
      regUserAgentPhone: `137${String(i).padStart(8, '0')}`,
      regUserAgentEmail: `agent${i}@example.com`,
      regUserAgentAddress: `代理地址 ${i}`,
      regUserAgentRemark: `代理备注 ${i}`,
      regUserAgentStatus: '1',
      regUserAgentCreateTime: new Date(Date.now() - Math.floor(Math.random() * 5000000000)).toISOString(),
      regUserAgentUpdateTime: new Date(Date.now() - Math.floor(Math.random() * 2500000000)).toISOString(),
    });
  }

  return data;
};

let mockUsersV2 = generateMockUserData();

const mockRoles = [
  { id: '1', roleName: '管理员', roleCode: 'admin', description: '系统最高权限' },
  { id: '2', roleName: '普通用户', roleCode: 'user', description: '普通用户权限' },
  { id: '3', roleName: '访客', roleCode: 'guest', description: '仅浏览权限' },
];

export default {
  // 登录接口
  'POST /api/login': async (req: any, res: any) => {
    await waitTime(500);
    const { account, password } = req.body;

    // 查找用户
    const user = mockUsers.find(
        (u) => u.account === account && u.password === password,
    );

    if (user) {
      res.json({
        success: true,
        data: {
          token: 'mock-token-' + user.userid,
          currentAuthority: user.role,
        },
        status: 'ok',
        type: req.body.type,
      });
    } else {
      res.status(401).json({
        success: false,
        status: 'error',
        type: req.body.type,
        message: '账户或密码错误',
      });
    }
  },

  // 获取用户信息接口
  'GET /api/getInfo': (req: any, res: any) => {
    // 从请求头获取 token
    const authorization = req.headers.authorization;

    if (!authorization) {
      res.status(401).json({
        success: false,
        errorMessage: '未登录或登录已过期',
        errorCode: 401,
      });
      return;
    }

    // 解析 token 获取 userid
    const token = authorization.replace('Bearer ', '');
    const userid = token.replace('mock-token-', '');

    // 根据 userid 查找用户
    const user = mockUsers.find((u) => u.userid === userid);

    if (!user) {
      res.status(401).json({
        success: false,
        errorMessage: 'Token 无效',
        errorCode: 401,
      });
      return;
    }

    res.json({
      success: true,
      data: {
        user: {
          userName: user.userName,
          avatar: user.avatar,
          userid: user.userid,
          email: user.email,
          signature: user.signature,
          title: user.title,
          group: user.group,
          role: user.role,
        },
        permissions: user.permissions,
        role: user.role,
      },
      errorCode: 0,
    });
  },

  // 退出登录接口
  'POST /api/logout': async (req: any, res: any) => {
    await waitTime(200);
    res.json({
      success: true,
      data: {},
      errorCode: 0,
    });
  },

  /**
   * 新-------------------------------------------
   * @param req
   * @param res
   * @constructor
   */

  // 获取用户列表
  'GET /sys/user/list': async (req: any, res: any) => {
    await waitTime(500);

    const { current = 1, pageSize = 10, account, realname, phone, email, status } = req.query;

    let filteredUsers = [...mockUsersV2];

    // 应用查询条件
    if (account) {
      filteredUsers = filteredUsers.filter(u => u.account.includes(account));
    }
    if (realname) {
      filteredUsers = filteredUsers.filter(u => u.realname.includes(realname));
    }
    if (phone) {
      filteredUsers = filteredUsers.filter(u => u.phone.includes(phone));
    }
    if (email) {
      filteredUsers = filteredUsers.filter(u => u.email.includes(email));
    }
    if (status) {
      filteredUsers = filteredUsers.filter(u => u.status.toString() === status);
    }

    // 分页
    const start = (parseInt(current) - 1) * parseInt(pageSize);
    const end = start + parseInt(pageSize);
    const paginatedData = filteredUsers.slice(start, end);

    res.json({
      success: true,
      message: '获取成功',
      result: {
        records: paginatedData,
        total: filteredUsers.length,
      },
    });
  },

  // 删除单个用户
  'DELETE /sys/user/delete': async (req: any, res: any) => {
    await waitTime(300);
    const { id } = req.query;

    const index = mockUsersV2.findIndex(u => u.id.toString() === id);
    if (index > -1) {
      mockUsersV2.splice(index, 1);
      res.json({
        success: true,
        message: '删除成功',
      });
    } else {
      res.status(404).json({
        success: false,
        message: '未找到用户',
      });
    }
  },

  // 批量删除用户
  'DELETE /sys/user/deleteBatch': async (req: any, res: any) => {
    await waitTime(500);
    const { ids } = req.query;
    const idList = ids.split(',');

    const initialLength = mockUsersV2.length;
    idList.forEach((id: string) => {
      const index = mockUsersV2.findIndex(u => u.id.toString() === id);
      if (index > -1) {
        mockUsersV2.splice(index, 1);
      }
    });
    const deletedCount = initialLength - mockUsersV2.length;

    res.json({
      success: deletedCount > 0,
      message: `成功删除 ${deletedCount} 条记录`,
    });
  },

  // 重置用户密码
  'PUT /sys/user/password/reset': async (req: any, res: any) => {
    await waitTime(300);
    const { id, password } = req.query; // 或 req.body
    console.log(`重置用户 ${id} 的密码为 ${password}`); // Mock 操作
    res.json({
      success: true,
      message: '密码重置成功',
    });
  },

  // 更新用户状态 (冻结/解冻)
  'PUT /sys/user/updateStatus': async (req: any, res: any) => {
    await waitTime(300);
    const { id, status } = req.query; // 或 req.body
    const user = mockUsersV2.find(u => u.id.toString() === id);

    if (user) {
      user.status = parseInt(status);
      user.status_dictText = parseInt(status) === 1 ? '正常' : '冻结';
      res.json({
        success: true,
        message: parseInt(status) === 1 ? '解冻成功' : '冻结成功',
      });
    } else {
      res.status(404).json({
        success: false,
        message: '未找到用户',
      });
    }
  },

  // 批量冻结/解冻用户
  'PUT /sys/user/batchUpdateStatus': async (req: any, res: any) => {
    await waitTime(500);
    const { ids, status } = req.query; // 或 req.body
    const idList = ids.split(',');

    const initialCount = mockUsersV2.filter(u => idList.includes(u.id.toString()) && u.status !== parseInt(status)).length;
    idList.forEach((id: string) => {
      const user = mockUsersV2.find(u => u.id.toString() === id);
      if (user) {
        user.status = parseInt(status);
        user.status_dictText = parseInt(status) === 1 ? '正常' : '冻结';
      }
    });

    res.json({
      success: initialCount > 0,
      message: `成功${parseInt(status) === 1 ? '解冻' : '冻结'} ${initialCount} 条记录`,
    });
  },

  // 获取用户信息 (用于编辑/详情)
  'GET /sys/user/queryById/:id': async (req: any, res: any) => {
    await waitTime(300);
    const { id } = req.params;
    const user = mockUsersV2.find(u => u.id.toString() === id);

    if (user) {
      res.json({
        success: true,
        message: '获取成功',
        result: user,
      });
    } else {
      res.status(404).json({
        success: false,
        message: '未找到用户',
      });
    }
  },

  // 添加用户
  'POST /sys/user/add': async (req: any, res: any) => {
    await waitTime(500);
    const data = req.body;

    // 检查唯一性 (Mock)
    if (mockUsersV2.some(u => u.account === data.account)) {
      res.status(400).json({
        success: false,
        message: '用户名已存在',
      });
      return;
    }
    if (mockUsersV2.some(u => u.phone === data.phone)) {
      res.status(400).json({
        success: false,
        message: '手机号已存在',
      });
      return;
    }
    if (mockUsersV2.some(u => u.email === data.email)) {
      res.status(400).json({
        success: false,
        message: '邮箱已存在',
      });
      return;
    }

    const newUser = {
      ...data,
      id: mockUsersV2.length + 1,
      status: 1, // 默认正常
      status_dictText: '正常',
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
    };
    mockUsersV2.push(newUser);

    res.json({
      success: true,
      message: '新增成功',
      result: newUser,
    });
  },

  // 编辑用户
  'PUT /sys/user/edit': async (req: any, res: any) => {
    await waitTime(500);
    const data = req.body;
    const index = mockUsersV2.findIndex(u => u.id.toString() === data.id);

    if (index > -1) {
      // 检查唯一性 (排除自己) (Mock)
      if (mockUsersV2.some((u, i) => u.account === data.account && i !== index)) {
        res.status(400).json({
          success: false,
          message: '用户名已存在',
        });
        return;
      }
      if (mockUsersV2.some((u, i) => u.phone === data.phone && i !== index)) {
        res.status(400).json({
          success: false,
          message: '手机号已存在',
        });
        return;
      }
      if (mockUsersV2.some((u, i) => u.email === data.email && i !== index)) {
        res.status(400).json({
          success: false,
          message: '邮箱已存在',
        });
        return;
      }

      mockUsersV2[index] = { ...mockUsersV2[index], ...data, updateTime: new Date().toISOString() };

      res.json({
        success: true,
        message: '编辑成功',
        result: mockUsersV2[index],
      });
    } else {
      res.status(404).json({
        success: false,
        message: '未找到用户',
      });
    }
  },

  // 检查唯一性 (用户名、手机号、邮箱)
  'POST /sys/checkOnly': async (req: any, res: any) => {
    await waitTime(300);
    const { tableName, fieldName, fieldVal, dataId } = req.body;
    let isDuplicate = false;
    if (tableName === 'sys_user') {
      if (fieldName === 'account') {
        isDuplicate = mockUsersV2.some(u => u.account === fieldVal && u.id.toString() !== dataId);
      } else if (fieldName === 'phone') {
        isDuplicate = mockUsersV2.some(u => u.phone === fieldVal && u.id.toString() !== dataId);
      } else if (fieldName === 'email') {
        isDuplicate = mockUsersV2.some(u => u.email === fieldVal && u.id.toString() !== dataId);
      }
    }

    res.json({
      success: !isDuplicate,
      message: isDuplicate ? `${fieldName}已存在` : `${fieldName}可用`,
    });
  },

  // 获取角色列表 (如果需要)
  'GET /sys/role/list': async (req: any, res: any) => {
    await waitTime(500);

    const { current = 1, pageSize = 10, roleName, roleCode } = req.query;

    let filteredRoles = [...mockRoles];

    if (roleName) {
      filteredRoles = filteredRoles.filter(r => r.roleName.includes(roleName));
    }
    if (roleCode) {
      filteredRoles = filteredRoles.filter(r => r.roleCode.includes(roleCode));
    }

    const start = (parseInt(current) - 1) * parseInt(pageSize);
    const end = start + parseInt(pageSize);
    const paginatedData = filteredRoles.slice(start, end);

    res.json({
      success: true,
      message: '获取成功',
      result: {
        records: paginatedData,
        total: filteredRoles.length,
      },
    });
  },

  // 获取所有角色 (如果需要)
  'GET /sys/role/queryall': async (req: any, res: any) => {
    await waitTime(300);
    res.json({
      success: true,
      message: '获取成功',
      result: mockRoles,
    });
  },
};